/**
 *  created by jsq on 2017/12/18
 *  refactoring by zhouli
 *  这页面重构比新开发差不多
 */
import React from 'react';
import {connect} from 'react-redux';
import {Button, Input, Select, Switch, DatePicker, Icon, Badge, message, Form, Row, Col} from 'antd';
import vendorService from 'containers/financial-management/supplier-management/vendorService';
import 'styles/financial-management/supplier-management/new-update-supplier.scss';
import Chooser from 'components/chooser';
import {deepFullCopy, messages} from "share/common";
import {LanguageInput} from 'components/index';
import moment from 'moment';
import {
  supplierModel,
} from 'containers/financial-management/supplier-management/supplier.model';

const {TextArea} = Input;
const FormItem = Form.Item;
const Option = Select.Option;

class NewUpdateSupplier extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      loading: false,
      basicInfo: {},
    };
  }

  componentWillMount() {
    // let params = this.props.params;
    // if (typeof params.id !== 'undefined') {
    //   params._venType = (params.venType === 1001 ? true : false)
    // }
    this.getSystemValueList(2216)
      .then(res => {
        this.setState({
          ctripList: res.data.values
        })
      });
  }

  componentDidMount() {
    this.getCodingRule(() => {
      let params = Object.assign({}, this.props.params);
      this.props.form.resetFields();
      this.initBasicInfo(params)
    });
  }

  componentWillReceiveProps(nextProps) {
    let params = nextProps.params;
    this.initBasicInfo(params);
  }

  initBasicInfo = (params) => {
    if (JSON.stringify(params) !== '{}' && params.flag !== "create") {
      params._venType = (params.venType === 1001 ? true : false);
      this.setState({
        basicInfo: params,
      }, () => {
        console.log(params)
      })
    } else {
      this.setState({
        loading: false,
        basicInfo: deepFullCopy(supplierModel),
      })
    }
  };

  //判断是否是手动编码
  getCodingRule = (fn) => {
    vendorService.getCodingRule()
      .then(res => {
        //是否为手动编码
        //返回false代表手动
        let basicInfo = this.state.basicInfo;
        basicInfo.autoCodeMark = res.data.result;
        this.setState({
          basicInfo,
        }, () => {
          fn()
        });
      })
  };

  //更新
  updateVendorInfo = (vender) => {
    vendorService.updateVendorInfo(vender)
      .then((response) => {
        if (response.data.msg === '成功' || response.data.code === '0000') {
          this.props.form.resetFields();
          this.setState({loading: false});
          this.props.close(true);
          message.success(`${messages("common.operate.success")}`);
        } else {
          this.setState({loading: false});
          message.error(`${messages("common.operate.filed")}, ${response.data.msg}`);
        }
      })
      .catch(e => {
        message.error(`${messages("common.operate.filed")}, ${e.response.data.message}`);
        this.setState({loading: false})
      })
  };
  //新增
  addVendorInfo = (vender) => {
    vendorService.addVendorInfo(vender)
      .then((response) => {
        if (response.data.msg === '成功' || response.data.code === '0000') {
          this.props.form.resetFields();
          this.setState({loading: false});
          this.props.close(true);
          message.success(`${messages("common.save.success", {name: ""})}`);
        } else {
          this.setState({loading: false});
          message.error(`${messages("common.save.filed")}, ${response.data.msg}`);
        }
      })
      .catch(e => {
        message.error(`${messages("common.save.filed")}, ${e.response.data.message}`);
        this.setState({loading: false})
      })
  }
  //提交
  handleSubmit = (e) => {
    e.preventDefault();
    this.props.form.validateFieldsAndScroll((err, values) => {
      if (!err) {
        console.log(values);
        let basicInfo = this.state.basicInfo;
        this.setState({loading: true});
        values.venType = basicInfo._venType ? 1001 : 1002;
        values.employeeID = this.props.user.employeeID;
        values.venderTypeId = values.venTypes && values.venTypes[0] ? values.venTypes[0].id : null;
        if (values.effectiveDate && values.effectiveDate.format) {
          values.effectiveDate = new Date(values.effectiveDate.format('YYYY-MM-DD')).getTime();
        } else {
          values.effectiveDate = null;
        }
        values.venOperatorNumber = this.props.user.employeeID;
        values.venOperatorName = this.props.user.fullName;
        let source = "COMPANY";
        if (this.props.main.tenantMode) {
          source = "TENANT";
        }
        values.source = source;
        values.i18n = basicInfo.i18n;
        if (basicInfo.id) {
          values.id = basicInfo.id;
          this.updateVendorInfo(values)
        } else {
          this.addVendorInfo(values)
        }
      }
    })
  };

  handleCancel = () => {
    this.props.form.resetFields();
    this.props.close(false);
  };
  //状态
  switchCardStatusChange = (e) => {
    let basicInfo = this.state.basicInfo;
    basicInfo._venType = e;
    this.setState({
      loading: false,
      basicInfo
    })
  };
  //过期时间
  handleCardTimeChange = (e) => {
    let basicInfo = this.state.basicInfo;
    basicInfo.effectiveDate = e ? e.format() : null;
    this.setState({
      loading: false,
      basicInfo
    })
  };

  i18nChange = (name, i18nName) => {
    let basicInfo = this.state.basicInfo;
    basicInfo.venNickname = name;
    basicInfo.i18n = {
      venNickname: i18nName
    };
    // this.setState({
    //   basicInfo,
    // })
  }

  render() {
    const {basicInfo, loading} = this.state;
    const {getFieldDecorator} = this.props.form;
    const formItemLayout = {
      labelCol: {span: 6},
      wrapperCol: {span: 14, offset: 0},
    };
    return (
      <div className="new-update-supplier">
        <Form onSubmit={this.handleSubmit}>
          <div className="new-update-supplier-basic">
            <div className="basic-icon"/>
            <div className="basic-title">
              {messages('financial-management.key314'/*基础信息*/)}
            </div>
            <div className="basic-content">
              <FormItem {...formItemLayout}
                        label={messages('financial-management.key325'/*供应商类型*/)}>
                {getFieldDecorator('venTypes', {
                  initialValue: basicInfo.venderTypeName ? [{
                    id: basicInfo.venderTypeId,
                    name: basicInfo.venderTypeName,
                  }] : undefined,
                  rules: [{
                    required: true,
                    message: messages('common.please.select')  //请选择
                  }]
                })(
                  <Chooser placeholder={messages('common.please.select')}
                           type={'vendor_type'}
                           valueKey={'id'}
                           labelKey={'name'}
                           listExtraParams={{isEnabled: true}}
                           single={true}/>
                )}
              </FormItem>


              <FormItem {...formItemLayout}
                        label={messages('financial-management.key326'/*供应商代码*/)}>
                {getFieldDecorator('venderCode', {
                  initialValue: basicInfo.venderCode
                })(
                  <Input disabled={basicInfo.autoCodeMark || basicInfo.id}
                         placeholder={messages('common.please.enter')/* 请输入 */}/>
                )}
              </FormItem>


              <FormItem {...formItemLayout} label={messages('financial-management.key327'/*供应商名称*/)}>
                {getFieldDecorator('venNickname', {
                  initialValue: basicInfo.venNickname,
                  rules: [{
                    required: true,
                    message: messages('common.please.enter')  //请输入
                  }]
                })(
                  <div>
                    <LanguageInput
                      name={basicInfo.venNickname}
                      i18nName={basicInfo.i18n ? basicInfo.i18n.venNickname : undefined}
                      isEdit={basicInfo.id}
                      nameChange={this.i18nChange}
                    />
                  </div>
                )}
              </FormItem>

              <FormItem {...formItemLayout} label={messages('financial-management.key328'/*启用日期*/)}>
                {getFieldDecorator('effectiveDate', {
                  initialValue: basicInfo.effectiveDate ? moment(basicInfo.effectiveDate) : undefined,
                })(
                  <DatePicker
                    format={'YYYY-MM-DD'}
                    onChange={this.handleCardTimeChange}/>
                )}
              </FormItem>
              {/*状态*/}
              <FormItem {...formItemLayout}
                        label={messages("common.column.status")} colon={true}>
                {getFieldDecorator('_venType', {
                  initialValue: basicInfo._venType
                })(
                  <div>
                    <Switch
                      defaultChecked={basicInfo._venType}
                      checked={basicInfo._venType}
                      checkedChildren={<Icon type="check"/>}
                      unCheckedChildren={<Icon type="cross"/>}
                      onChange={this.switchCardStatusChange}/>
                    <span className="enabled-type" style={{
                      marginLeft: 20,
                      width: 100
                    }}>{basicInfo.venType ? messages("common.status.enable") : messages("common.disabled")}</span>
                  </div>)}
              </FormItem>
            </div>
          </div>
          <div className="new-update-supplier-other">
            <div className="other-icon"/>
            <div className="other-title">
              {messages('financial-management.key336'/*其它信息*/)}
            </div>
            <div className="other-content">

              <FormItem {...formItemLayout} label={messages('financial-management.key329'/*法人代表*/)}>
                {getFieldDecorator('artificialPerson', {
                  initialValue: basicInfo.artificialPerson
                })(
                  <Input placeholder={messages('common.please.enter')/* 请输入 */}/>
                )}
              </FormItem>
              <FormItem {...formItemLayout} label={messages('financial-management.key330'/*税务登记号*/)}>
                {getFieldDecorator('taxIdNumber', {
                  initialValue: basicInfo.taxIdNumber
                })(
                  <Input placeholder={messages('common.please.enter')/* 请输入 */}/>
                )}
              </FormItem>
              <FormItem {...formItemLayout} label={messages('financial-management.key331'/*联系人*/)}>
                {getFieldDecorator('contact', {
                  initialValue: basicInfo.contact
                })(
                  <Input placeholder={messages('common.please.enter')/* 请输入 */}/>
                )}
              </FormItem>
              <FormItem {...formItemLayout} label={messages('financial-management.key332'/*联系人电话*/)}>
                {getFieldDecorator('contactPhone', {
                  initialValue: basicInfo.contactPhone
                })(
                  <Input placeholder={messages('common.please.enter')/* 请输入 */}/>
                )}
              </FormItem>

              <FormItem {...formItemLayout} label={messages('financial-management.key333'/*邮箱*/)}>
                {getFieldDecorator('contactMail', {
                  initialValue: basicInfo.contactMail
                })(
                  <Input placeholder={messages('common.please.enter')/* 请输入 */}/>
                )}
              </FormItem>
              <FormItem {...formItemLayout} label={messages('financial-management.key334'/*传真*/)}>
                {getFieldDecorator('fax', {
                  initialValue: basicInfo.fax
                })(
                  <Input placeholder={messages('common.please.enter')/* 请输入 */}/>
                )}
              </FormItem>
              <FormItem {...formItemLayout} label={messages('financial-management.key335'/*地址*/)}>
                {getFieldDecorator('address', {
                  initialValue: basicInfo.address,
                  rules: [{
                    max: 200,
                    message: messages('financial-management.key921')/*不能超过200字*/
                  }]
                })(
                  <Input placeholder={messages('common.please.enter')/* 请输入 */}/>
                )}
              </FormItem>

              <FormItem {...formItemLayout} label={messages('financial-management.key322'/*备注*/)}>
                {getFieldDecorator('notes', {
                  initialValue: basicInfo.notes,
                  rules: [{
                    max: 200,
                    message: messages('financial-management.key921')/*不能超过200字*/
                  }]
                })(
                  <TextArea placeholder={messages('common.please.enter')}/>
                )}
              </FormItem>
            </div>
          </div>
          <div className="slide-footer">
            <Button type="primary" htmlType="submit" loading={loading}>
              {messages('common.save')}
            </Button>
            <Button onClick={this.handleCancel}>
              {messages('common.cancel')}
            </Button>
          </div>
        </Form>
      </div>)
  }
}

NewUpdateSupplier.contextTypes = {
  router: React.PropTypes.object
};

function mapStateToProps(state) {
  return {
    main: state.main,
    language: state.main.language,
    user: state.login.user
  }
}

const WrappedNewUpdateSupplier = Form.create()(NewUpdateSupplier);

export default connect(mapStateToProps)(WrappedNewUpdateSupplier);
